package com.shujia.day19.udpdemo2;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
    1:建立udp的socket服务.
    2:通过receive方法接收数据
    3:将收到的数据存储到数据包对象中
    4:通过数据包对象的功能来完成对接收到数据进行解析.
    5:可以对资源进行关闭

 */
public class ReceiveDemo1 {
    public static void main(String[] args) throws Exception{
        // 1:建立udp的socket服务
        DatagramSocket socket = new DatagramSocket(10086);
        System.out.println("=================== 欢迎来到32期大群聊 =======================");

        while (true){
            // 2:通过receive方法接收数据
            //public synchronized void receive(DatagramPacket p)
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            socket.receive(packet);

            //4:通过数据包对象的功能来完成对接收到数据进行解析.
            byte[] data = packet.getData();
            int length = packet.getLength();
            String info = new String(data, 0, length);

            InetAddress address = packet.getAddress();
            String hostName = address.getHostName();
            BufferedWriter bw = new BufferedWriter(new FileWriter("java/src/com/shujia/day19/recode/" + hostName + ".txt",true));

            if("886".equals(info)){
                System.out.println("----------- 提示线 -------------");
                System.out.println(hostName+" 用户已离开群聊.....");
                System.out.println("----------- 提示线 -------------");
//                break;
            }else {
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                System.out.println(time);
                System.out.println(hostName+ "："+info);
                bw.write(time);
                bw.newLine();
                bw.write(info);
                bw.newLine();
                bw.flush();

                System.out.println();
            }
        }


        // 5:可以对资源进行关闭
//        socket.close();

    }
}
